package cotrollor;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String blogId = req.getParameter("blogId");

        // 请求来自博客列表页,返回登录的用户信息
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null || user.equals("")) {
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前用户未登录");
            return;
        }

        if (blogId == null) {
            // 用户不为空，返回用户信息,返回信息不涉及用户密码,设置为空
            user.setPassword("");
            resp.setContentType("application/json;charset=utf8");
            String jsonString = objectMapper.writeValueAsString(user);
            resp.getWriter().write(jsonString);
        } else {
            // 请求来自博客详情页,返回作者信息
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.select(Integer.parseInt(blogId));
            if (blog == null) {
                resp.setStatus(403);
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("当前blogId有误");
                return;
            }
            UserDao userDao = new UserDao();
            int userId = blog.getUserId();
            // 根据博客获取的作者信息
            User author = userDao.select(userId);
            if (author == null) {
                resp.setStatus(403);
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("当前博客对应的作者未找到");
                return;
            }
            // 返回信息不涉及用户密码,设置为空
            author.setPassword("");
            if (author.getUserId() == user.getUserId()) {
                author.setIsYourBlog(1);
            } else {
                author.setIsYourBlog(0);
            }
            resp.setContentType("application/json;charset=utf8");
            String jsonString = objectMapper.writeValueAsString(author);
            resp.getWriter().write(jsonString);
        }
    }
}
